package vy.org.app.page.member;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.vy.dal.DALCtx;
import org.vy.dal.dao.ViewVyLookupPatrikaPeriodDAO;
import org.vy.dal.dao.ViewVyLookupPatrikaPeriodDO;
import org.vy.dal.dao.VyAddressDAO;
import org.vy.dal.dao.VyAddressDO;
import org.vy.dal.dao.VyDabbaSubscriptionDAO;
import org.vy.dal.dao.VyDabbaSubscriptionDO;
import org.vy.dal.dao.VyMagazineSubscriptionDAO;
import org.vy.dal.dao.VyMagazineSubscriptionDO;
import org.vy.dal.dao.VyMemberDAO;
import org.vy.dal.dao.VyMemberDO;
import org.vy.dal.dao.lookup.VyLookupDeliveryModeDAO;
import org.vy.dal.dao.lookup.VyLookupDeliveryModeDO;
import org.vy.dal.dao.lookup.VyLookupPatrikaDAO;
import org.vy.dal.dao.lookup.VyLookupPatrikaDO;

import vy.org.app.common.ActionCtx;
import vy.org.app.common.AddressTypeEnum;
import vy.org.app.common.BaseAction;
import vy.org.app.common.DabbaIdGenerator;
import vy.org.app.common.IdTypeEnum;
import vy.org.app.common.ModuleEnum;
import vy.org.app.common.SubscriptionIdGenerator;
import vy.org.app.common.VyIdGenerator;
import vy.org.app.page.address.AddressHelper;
import vy.org.app.page.lookup.delivery.DeliveryModeHelper;
import vy.org.app.page.lookup.delivery.MntnDeliveryModeForm;
import vy.org.app.page.lookup.patrika.MntnPatrikaPeriodForm;
import vy.org.app.page.lookup.patrika.PatrikaHelper;
import vy.org.app.page.subscription.dabba.DabbaForm;
import vy.org.app.page.subscription.dabba.DabbaHelper;
import vy.org.app.page.subscription.magazine.MagazineForm;
import vy.org.app.page.subscription.magazine.MagazineHelper;

public class SaveMemberAction extends BaseAction {

	@Override
	public ActionForward executeAction(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) {

		if(!ActionCtx.ctx().getUser().hasAccessToModule(String.valueOf(ModuleEnum.ADD_MEMBER.getId()))
				&& !ActionCtx.ctx().getUser().hasAccessToModule(String.valueOf(ModuleEnum.EDIT_MEMBER.getId()))){
			return mapping.findForward("illegalaccess");
		}

		MemberForm form = (MemberForm)actionForm;
		try{
			List<VyLookupPatrikaDO> patrikaLst = VyLookupPatrikaDAO.findAllActive();
			List<VyLookupDeliveryModeDO> deliveryModeLst = VyLookupDeliveryModeDAO.findAllActive();
			List<ViewVyLookupPatrikaPeriodDO> patPeriodLst = ViewVyLookupPatrikaPeriodDAO.findAllActive();
			
			Map<String, List<MntnPatrikaPeriodForm>> patrikaMap = new HashMap<String, List<MntnPatrikaPeriodForm>>(); 
			Map<String, MntnDeliveryModeForm> delModeMap = new HashMap<String, MntnDeliveryModeForm>(); 
			
			for(VyLookupPatrikaDO pat : patrikaLst){
				patrikaMap.put(pat.getPatrikaId().toString(), PatrikaHelper.fillPatrikaPeriodForm(pat, patPeriodLst));
			}
			for(VyLookupDeliveryModeDO dl : deliveryModeLst){
				delModeMap.put(dl.getDeliveryModeCode(), DeliveryModeHelper.fillPatrikaForm(dl));
			}
			form.setPatrikas(patrikaMap);
			form.setDeliveryModes(delModeMap);
		}catch(Exception e){
			e.printStackTrace();
		}
		
		if("LANG".equals(request.getParameter("mode"))){
			//Should show back the same page with changed language
			return mapping.findForward("failure");
		}
		
		VyMemberDO memDO = MemberHelper.fillMemberDO(form);
		List<VyAddressDO> lstAddr = new ArrayList<VyAddressDO>();
		lstAddr.add(AddressHelper.getAddressDO(form.getOfficeAddress()));
		lstAddr.add(AddressHelper.getAddressDO(form.getPermanentAddress()));
		lstAddr.add(AddressHelper.getAddressDO(form.getPresentAddress()));
		try{
			DALCtx.ctx().beginTransaction();
			
			for(VyAddressDO addr : lstAddr){
				if(addr.getAddressId() != null && addr.getAddressId() > 0){
					VyAddressDAO.update(addr);
				}else{
					VyAddressDAO.insert(addr);
				}
			}
			memDO.setOfficeAddressId(lstAddr.get(0).getAddressId());
			memDO.setPermanentAddressId(lstAddr.get(1).getAddressId());
			memDO.setPresentAddressId(lstAddr.get(2).getAddressId());
			
			if(memDO.getVyId() != null && !"".equals(memDO.getVyId().trim())){
				VyMemberDAO.update(memDO);
			}else{
				String vyId = VyIdGenerator.generateId(memDO, lstAddr);
				memDO.setVyId(vyId);
				VyMemberDAO.insert(memDO);
			}
			
			int cntM = form.getMagazineSubscriptionCnt();
			if(form.getMagazines() != null && cntM > 0){
				List<MagazineForm> magazines = form.getMagazines();
				for(MagazineForm mzForm : magazines){
					if(mzForm.getPatrikaId()==null || "".equals(mzForm.getPatrikaId().trim()))
						continue;
					VyMagazineSubscriptionDO mzDO = MagazineHelper.fillMagazineDO(mzForm);
					if( AddressTypeEnum.OFFICE.getName().equals(mzForm.getAddress().getAddressType())){
						mzDO.setAddressId(memDO.getOfficeAddressId().toString());
					}else if( AddressTypeEnum.PRESENT.getName().equals(mzForm.getAddress().getAddressType())){
						mzDO.setAddressId(memDO.getPresentAddressId().toString());
					}else if( AddressTypeEnum.PERMANENT.getName().equals(mzForm.getAddress().getAddressType())){
						mzDO.setAddressId(memDO.getPermanentAddressId().toString());
					}
					mzDO.setVyId(memDO.getVyId());
					if(mzDO.getSubscriptionId() != null && !"".equals(mzDO.getSubscriptionId().trim())){
						VyMagazineSubscriptionDAO.update(mzDO);
					}else{
						String subId = SubscriptionIdGenerator.generateId(mzDO, 
								mzDO.getReceiptDate(), mzForm.getAddress().getCountry(), mzForm.getAddress().getStateOrRegion());
						mzDO.setSubscriptionId(subId);
						VyMagazineSubscriptionDAO.insert(mzDO);
					}
					cntM--;
					if(cntM==0) break;
				}
			}

			int cntD = form.getDabbaSubscriptionCnt();
			if(form.getDabbas() != null && cntD > 0){
				List<DabbaForm> dabbas = form.getDabbas();
				for(DabbaForm daForm : dabbas){
					if(daForm.getDabbaKey()==null || "".equals(daForm.getDabbaKey().trim()))
						continue;
					VyDabbaSubscriptionDO daDO = DabbaHelper.fillDabbaDO(daForm);
					daDO.setSubscriberId(memDO.getVyId());
					daDO.setIdType(IdTypeEnum.MEMBER.getId());
					if(daDO.getDabbaSubscriptionId() != null && !"".equals(daDO.getDabbaSubscriptionId().trim())){
						VyDabbaSubscriptionDAO.update(daDO);
					}else{
						String subId = DabbaIdGenerator.generateId(daDO, daForm.getAddress().getCountry(), daForm.getAddress().getStateOrRegion());
						daDO.setDabbaSubscriptionId(subId);
						VyDabbaSubscriptionDAO.insert(daDO);
					}
					cntD--;
					if(cntD==0) break;
				}
			}
			
			DALCtx.ctx().commitTransaction();
			
		}catch(Exception e){
			DALCtx.ctx().rollbackTransaction();
			e.printStackTrace();
			return mapping.findForward("failure");
		}
		
		return mapping.findForward("success");
	}

	@Override
	protected ModuleEnum getModuleId() {
		return null;
	}
	
}
